﻿using Pulog.Models;
using System.Linq;
using System.Collections.Generic;

namespace Pulog.Models
{
    public partial class CategoryRepository : ICategoryRepository
    {
        private readonly PulogDataContext dc = new PulogDataContext();

        public List<Category> GetAllCategories()
        {
            return dc.Categories.ToList<Category>();
        }

        public Category GetCategoryByID(int id)
        {
            return dc.Categories.Single(c => c.categoryID == id);
        }

        public List<string> GetCategoriesByPostId(int id)
        {
            List<string> cats = new List<string>();
            cats.Add(dc.Posts.Single(p => p.postID==id).Category.categoryName);
            return cats;
        }

        public void AddCategory(Category category)
        {
            dc.Categories.InsertOnSubmit(category);
        }

        public void DeleteCategoryWithAllPosts(Category category)
        {
            foreach (Post p in category.Posts)
            {
                dc.Comments.DeleteAllOnSubmit(p.Comments);
            }
            dc.Posts.DeleteAllOnSubmit(category.Posts);
            dc.Categories.DeleteOnSubmit(category);
        }

        // Persistence 
        public void Save()
        {
            dc.SubmitChanges();
        }

    }
}